package han.chensing.latos.maker.windows.widget;

import com.badlogic.gdx.scenes.scene2d.ui.List;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.utils.ArraySelection;

import java.util.ArrayList;
import java.util.Objects;

import han.chensing.latos.maker.function.AsString;

public class CUIList<T> extends List<CUIList.CUIListItem<T>> {

    java.util.List<CUIListItem<T>> dataList;
    AsString<T> asString;

    public CUIList(Skin skin, AsString<T> asString) {
        super(skin);
        this.asString = asString;
        this.dataList=new ArrayList<>();
    }

    public java.util.List<CUIListItem<T>> getDataList() {
        return dataList;
    }

    public void setMultiSelective(boolean multiSelect){
        ArraySelection<CUIListItem<T>> selection = getSelection();
        selection.setRangeSelect(multiSelect);
        selection.setMultiple(multiSelect);
    }

    public void setDataList(java.util.List<T> dataList) {
        this.dataList.clear();
        for (T t : dataList) {
            CUIListItem<T> e = new CUIListItem<>();
            e.value=t;
            e.asString = asString;
            this.dataList.add(e);
        }
    }

    public void update(){
        if (dataList==null|| asString ==null)
            return;
        clearItems();
        for (CUIListItem<T> t:dataList)
            getItems().add(t);
        invalidateHierarchy();
    }

    public AsString<T> getAsStr() {
        return asString;
    }

    public static class CUIListItem<T>{
        AsString<T> asString;
        T value;
        @Override
        public String toString() {
            return asString.apply(value);
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            CUIListItem<?> CUIListItem = (CUIListItem<?>) o;
            return Objects.equals(value, CUIListItem.value);
        }
        public void setAsStr(AsString<T> asString) {
            this.asString = asString;
        }

        public AsString<T> getAsStr() {
            return asString;
        }

        public T getValue() {
            return value;
        }

        public void setValue(T value) {
            this.value = value;
        }
    }
}
